import 'package:df/utils/logger_utils.dart';
import 'package:df/utils/sp_key.dart';
import 'package:df/utils/sp_utils.dart';
import 'package:df/widgets/toast_utils.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:df/generated/l10n.dart';

/// https://juejin.cn/post/7172442692972969992
/// 字符串资源
class StringLocale extends ChangeNotifier {
  Locale? get locale => _locale;
  Locale? _locale = null;//zh、tw、en、vi、km、es

  static const String languageCN = 'zh';
  static const String languageTw = 'tw';
  static const String languageEN = 'en';
  static const String languageVi = 'vi';
  static const String languageKm = 'km';
  static const String languageEs = 'es';

  /// 初始化
  init() {
    String? spLanguage = SpUtils().get<String?>(SpKey.kJsLanguage);
    if (kDebugMode) {
      // ToastUtils.show('初始化Sp语言= $spLanguage');
      LogUtils.v('初始化Sp语言= $spLanguage');
    }
    String language = spLanguage ?? '';
    if (language == languageCN || language == languageTw) {
      _locale = const Locale(languageCN, '');
    } else if (language == languageEN) {
      _locale = const Locale(languageEN, '');
    } else if (language == languageVi) {
      _locale = const Locale(languageVi, '');
    } else if (language == languageKm) {
      _locale = const Locale(languageKm, '');
    } else if (language == languageEs) {
      _locale = const Locale(languageEs, '');
    } else {
      _locale = const Locale(languageCN, '');
      LogUtils.e('【调试】没有匹配到= $language');
    }
    LogUtils.d('【调试】Sp的语言= $language');
  }

  /// 设置语言
  setLocale(String? language) {
    String? oldLanguage = SpUtils().get<String?>(SpKey.kJsLanguage);
    String? defLanguage = oldLanguage ?? languageCN;

    String lan = language ?? defLanguage;
    Locale locale = const Locale(languageCN);
    if(lan == languageCN || lan == languageTw) {
      locale = Locale(languageCN, '');
    } else if(lan == languageEN) {
      locale = const Locale(languageEN);
    } else if(lan == languageVi) {
      locale = const Locale(languageVi);
    } else if(lan == languageKm) {
      locale = const Locale(languageKm);
    } else if(lan == languageEs) {
      locale = const Locale(languageEs);
    }
    _locale = locale;
    SpUtils().set(SpKey.kJsLanguage, lan);
    if (kDebugMode) {
      String? testLanguage = SpUtils().get<String?>(SpKey.kJsLanguage);
      // ToastUtils.show('存Sp语言= $testLanguage');
      LogUtils.v('存Sp语言= $testLanguage');
    }
    notifyListeners();
  }

  /// 获取实例
  static S create() {
    return S.current;
  }

}
